package com.alibaba.nacos.core.remote;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.remote.DefaultRequestFuture;
import com.alibaba.nacos.api.remote.response.Response;

import java.util.IllegalFormatCodePointException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RpcAckCallbackSynchronizer {

    public static final Map<String, Map<String, DefaultRequestFuture>> CALLBACK_CONTEXT = new ConcurrentHashMap<>();

    public static void clearFuture(String connectionId, String requestId) {
        CALLBACK_CONTEXT.computeIfPresent(connectionId, (k, v) -> {
            v.remove(requestId);
            return v.isEmpty() ? null : v;
        });
    }

    public static void ackNotify(String connectionId,
                                 Response response) {
        Map<String, DefaultRequestFuture> futureMap = CALLBACK_CONTEXT.get(connectionId);
        if (futureMap == null) {
            return;
        }

        DefaultRequestFuture future = futureMap.remove(response.getRequestId());
        if (future == null) {
            return;
        }

        if (response.isSuccess()) {
            future.setResponse(response);
        } else {
            future.setFailResult(new NacosException(response.getErrorCode(), response.getMessage()));
        }
    }

    public static void syncCallback(String connectionId,
                                    String requestId,
                                    DefaultRequestFuture requestFuture) throws NacosException {
        Map<String, DefaultRequestFuture> futureMap = CALLBACK_CONTEXT.computeIfAbsent(connectionId, k -> new ConcurrentHashMap<>());
        DefaultRequestFuture old = futureMap.putIfAbsent(requestId, requestFuture);
        if (old == null) {
            return;
        }

        throw new NacosException(NacosException.INVALID_PARAM, "request id conflict");
    }
}
